package com.webapi.common.utils;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.util.StringUtils;

/**
 * Generator Bean's name with a rule<br>
 * 1.if the Bean's name end with <code><b>"Impl"</b></code> , then it will replace with none<br>
 * 2.Bean's first letter will translate to lower case
 * <p>
 * for example:<br>
 * <code>UserServiceImpl -&gt userService</code><br>
 * <code>ADaoImpl -&gt aDao</code><br>
 * <code>BDao -&gt bDao</code>
 * <p>
 */
public class SpringBeanNameGenerator implements BeanNameGenerator {

	private static final String SUFFIX = "Impl";

	@Override
	public String generateBeanName(BeanDefinition paramBeanDefinition,
			BeanDefinitionRegistry paramBeanDefinitionRegistry) {
		
		return fix(paramBeanDefinition.getBeanClassName());
	}
	
	private String cut(String s) {
	    int end = s.contains(SUFFIX) ? s.lastIndexOf(SUFFIX) : s.length();
	    return s.substring(s.lastIndexOf(".") + 1, end);
	}
	
	private String fix(String s) {
        return StringUtils.uncapitalize(cut(s));
	}

}